package com.server;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Helper.FlightInfo;
import com.Helper.PaymentHelper;
import com.Helper.ReservationHelper;
import com.Helper.ReservationInfo;
import com.Helper.SeatHelper;


public class ModGeneralServlet extends CustomerServlet
{
	private static final long serialVersionUID = 1L;

	@Override
	//@requires HttpServletRequest !=NULL,  HttpServletResponse !=NULL ;
    //@assignable username,resID,first,last,meal,seat,flight,msg,prevSeat,prevFlgith;
    //@ensures (info.seat.equals(seat) && info.flightID.equals(flight);
	//@signals_only RuntimeException, IOException,ServletException;
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException
	{
		ConnectDB();

		String username = req.getParameter("username");
		String resID = req.getParameter("resID");
		String first = req.getParameter("firstName");
		String last = req.getParameter("lastName");
		String meal = req.getParameter("meal");
		String seatID = req.getParameter("seatID");
		String flightID = req.getParameter("flightID");
		String msg = null;
			
		try //system get the reservation number and if the seat is not taken,reservation is modified.
		{
			ReservationHelper.Setup(connection, username);
			SeatHelper.Setup(connection);
			PaymentHelper.Setup(connection);
			
			int id = Integer.parseInt(resID);
			ReservationInfo info = ReservationHelper.GetSelectedReservation(id);
			
			String prevSeat = info.seat;
			String prevFlight = info.flightID;
			
			ReservationHelper.ModFirstName(first, id);
			ReservationHelper.ModLastName(last, id);
			ReservationHelper.ModMeal(meal, id);
			
			if (SeatHelper.IsSeatReserved(seatID, flightID) && prevSeat.equals(seatID) == false)
			{
				msg = "SeatID " + seatID + " in " + flightID + " is reserved by another customer.";
				req.setAttribute("username", username);	
				req.setAttribute("msg", msg);
				req.getRequestDispatcher("reservation/payment_error.jsp").forward(req, resp);			
			}
			else
			{
				float price = PaymentHelper.GetPriceForSeat(seatID, flightID);
				
				ReservationHelper.ModSeat(seatID, id);
				
				
				SeatHelper.MarkEmpty(prevSeat, prevFlight);
				SeatHelper.MarkReserved(seatID, flightID);	
				req.setAttribute("username", username);	
				req.setAttribute("resID", resID);
				req.setAttribute("flightID", flightID);
				req.setAttribute("seatID", seatID);
				
				req.setAttribute("msg", msg);
				req.setAttribute("price", price);
				req.getRequestDispatcher("reservation/ModGeneral.jsp").forward(req, resp);
			}

		} 
		catch (SQLException e) 
		{

			e.printStackTrace();
		}
		
	}

}

